package com.cy.store.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



/**
 * 过滤器
 */
@Slf4j
@WebFilter("/*")
public class Glq implements Filter {


    @Override   // 过滤器需要实现这个方法
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // ?
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取uri
        String uri = request.getRequestURI();


        log.info("截取的uri：{}", uri);

        // 白名单
        String[] uris = new String[]{
                "/bootstrap3/**",
                "/css/**",
                "/images/**",
                "/js/**",
                "/web/login.html",
                "/users/reg",
                "/users/login",
                "/districts/**",
                "/products/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/favicon.ico"

        };

        // 判断路径是否匹配
        boolean pe = pe(uris, uri);

        // 如果匹配则放行
        if (pe){
            log.info("放行的路径：{}", uri);
            filterChain.doFilter(request, response);    // ?
            return;
        }

        // 如果已登录（查看session里是否有uid）也放行
        if(request.getSession().getAttribute("uid") != null){
            log.info("已登录用户的id：{}", request.getSession().getAttribute("uid"));

            log.info("放行的路径：{}", uri);

            filterChain.doFilter(request, response);    // ?
            return;
        }

        // 未登录跳转登录页面
        response.sendRedirect("/web/login.html");



    }


    /**
     * 工具类：匹配功能
      */
    public static final AntPathMatcher Matcher = new AntPathMatcher();

    /**
     * 查询路径是否匹配
     */
    public boolean pe(String[] uris, String uri){

        for(String u: uris) {
            boolean match = Matcher.match(u, uri);
            if(match){
                return true;
            }
        }

        return false;
    }

}
